<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="任务名称" prop="jobName">
        <el-input v-model="queryParams.jobName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务简称" prop="jobSimpleName">
        <el-input v-model="queryParams.jobSimpleName" placeholder="请输入任务简称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          plain
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          plain
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-has-permi="['tool:job:query']"
          type="info"
          icon="el-icon-s-operation"
          size="mini"
          plain
          @click="handleJobLog"
        >日志</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column label="任务名称" align="center" prop="jobName" min-width="130" :show-overflow-tooltip="true" />
      <el-table-column label="任务简称" align="center" prop="jobSimpleName" :show-overflow-tooltip="true" />
      <el-table-column label="任务分组" align="center" prop="jobGroup" :show-overflow-tooltip="true" />
      <el-table-column label="cron执行表达式" align="center" prop="cronExpression" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            active-text="正常"
            inactive-text="暂停"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-has-permi="['tool:job:remove']"
            style="color: red;"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-dropdown v-has-permi="['tool:job:query']" size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-has-permi="['tool:job:query']"
                icon="el-icon-view"
                command="handleView"
              >任务详细</el-dropdown-item>
              <el-dropdown-item
                v-has-permi="['tool:job:query']"
                icon="el-icon-s-operation"
                command="handleJobLog"
              >调度日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNumber"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 任务日志详细 -->
    <el-dialog title="任务详细" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称：">{{ form.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务简称：">{{ form.jobSimpleName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ form.jobGroup }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首次触发时间：">{{ form.startTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间：">{{ form.endTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次触发时间：">{{ form.previousFireTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次触发时间：">{{ form.nextFireTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ form.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">{{ statusFormat(form) }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <crontab v-if="form.cronExpression && form.cronExpression.split(' ').length === 7" :expression="form.cronExpression" :hideComponent="['second', 'min', 'hour', 'day', 'month', 'week', 'year']" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listJob, getJob, delJob, changeJobStatus } from '@/api/tool/job'
import Crontab from '@/components/Crontab'

export default {
  name: 'Job',
  components: { Crontab },
  dicts: ['sys_job_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 定时任务表格数据
      jobList: [],
      // 是否显示详细弹出层
      openView: false,
      // 查询参数
      queryParams: {
        pageNumber: 1,
        pageSize: 10,
        jobName: undefined,
        jobSimpleName: undefined,
        status: undefined
      },
      // 表单参数
      form: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询定时任务列表 */
    getList() {
      this.loading = true
      listJob(this.queryParams).then(res => {
        this.jobList = res.list
        this.total = Number(res.total)
        this.loading = false
      })
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.$selectDictLabel(this.dict.type.sys_job_status, row.status)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNumber = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleView':
          this.handleView(row)
          break
        case 'handleJobLog':
          this.handleJobLog(row)
          break
        default:
          break
      }
    },
    // 任务状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '暂停'
      this.$modal.confirm('确认要 "' + text + '" "' + row.jobName + '" 任务吗？').then(function() {
        return changeJobStatus(row.jobName, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    /** 任务详细信息 */
    handleView(row) {
      getJob(row.jobName).then(res => {
        this.form = res
        this.openView = true
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jobNames = row.jobName || this.ids
      this.$modal.confirm('是否确认删除定时任务名称为 "' + jobNames + '" 的数据项？').then(function() {
        return delJob(jobNames)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 任务日志列表查询 */
    handleJobLog(row) {
      const jobName = row.jobName || ''
      this.$router.push('/tool/job-log/index/' + jobName)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$download('tool/job/export', {
        ...this.queryParams
      }, `job_${new Date().getTime()}.xls`)
    }
  }
}
</script>
